#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试股票名称获取问题的测试脚本
"""

import akshare as ak
import pandas as pd

def test_stock_info_methods(stock_code="300558"):
    """测试多种获取股票信息的方法"""
    
    print(f"=== 测试股票代码: {stock_code} ===\n")
    
    # 方法1: stock_individual_info_em
    print("1. 测试 ak.stock_individual_info_em:")
    try:
        stock_info = ak.stock_individual_info_em(symbol=stock_code)
        print(f"   数据类型: {type(stock_info)}")
        print(f"   数据长度: {len(stock_info)}")
        print("   详细数据:")
        for i, row in stock_info.iterrows():
            item = str(row.get('item', ''))
            value = str(row.get('value', ''))
            print(f"     {item}: {value}")
            if '简称' in item or '名称' in item:
                print(f"   ★ 找到股票名称: {value}")
        print()
    except Exception as e:
        print(f"   错误: {e}\n")
    
    # 方法2: stock_info
    print("2. 测试 ak.stock_info_a_code_name:")
    try:
        all_stocks = ak.stock_info_a_code_name()
        stock_row = all_stocks[all_stocks['code'] == stock_code]
        if len(stock_row) > 0:
            stock_name = stock_row.iloc[0]['name']
            print(f"   ★ 找到股票名称: {stock_name}")
        else:
            print(f"   未找到股票代码 {stock_code}")
        print()
    except Exception as e:
        print(f"   错误: {e}\n")
    
    # 方法3: stock_zh_a_spot_em
    print("3. 测试 ak.stock_zh_a_spot_em (实时行情):")
    try:
        spot_data = ak.stock_zh_a_spot_em()
        stock_row = spot_data[spot_data['代码'] == stock_code]
        if len(stock_row) > 0:
            stock_name = stock_row.iloc[0]['名称']
            print(f"   ★ 找到股票名称: {stock_name}")
        else:
            print(f"   未找到股票代码 {stock_code}")
        print()
    except Exception as e:
        print(f"   错误: {e}\n")
    
    # 方法4: 尝试获取历史数据验证代码
    print("4. 测试历史数据验证:")
    try:
        from datetime import datetime, timedelta
        end_date = datetime.now().strftime('%Y%m%d')
        start_date = (datetime.now() - timedelta(days=7)).strftime('%Y%m%d')
        
        hist_data = ak.stock_zh_a_hist(
            symbol=stock_code, 
            period="daily", 
            start_date=start_date, 
            end_date=end_date, 
            adjust=""
        )
        
        if len(hist_data) > 0:
            print(f"   ✅ 股票代码有效，历史数据量: {len(hist_data)}")
            print(f"   最新收盘价: {hist_data.iloc[-1]['收盘']}")
        else:
            print(f"   ❌ 股票代码无效或无数据")
        print()
    except Exception as e:
        print(f"   错误: {e}\n")

def test_multiple_stocks():
    """测试多个股票代码"""
    test_codes = ["300558", "600519", "000001", "002594", "300750"]
    
    for code in test_codes:
        print(f"\n{'='*50}")
        test_stock_info_methods(code)

if __name__ == "__main__":
    print("开始调试股票名称获取问题...\n")
    
    # 重点测试300558
    test_stock_info_methods("300558")
    
    print("\n" + "="*50)
    print("测试其他股票代码进行对比:")
    test_multiple_stocks()